<!DOCTYPE html><!--suppress ALL-->
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>spring boot + websocket+广播式</title>

</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似你的浏览器不支持websocket</h2></noscript>

<div>
    <div>
        <button id="connect" onclick="connect()">连接</button>
        <button id="disconnect" disabled onclick="disconnect()">断开连接</button>
    </div>

    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name">
        <button id="sendName" onclick="sendName()">发送</button>
        <p id="response"></p>
    </div>
</div>

<script th:src="@{stomp.min.js}" type="text/javascript"></script>
<script th:src="@{sockjs.min.js}" type="text/javascript"></script>
<script th:src="@{jquery.min.js}" type="text/javascript"></script>
<script type="text/javascript">
    var stompClient = null;


    function setConnected(connected) {
        document.getElementById("connect").disabled = connected;
        document.getElementById("disconnect").disabled = !connected;
        // document.getElementById("conversationDiv").style.display = connected ? 'block' : 'none';
        document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }

    function connect() {
        var socket = new SockJS('/endpointWisely');//设置连接到SockJS的endpoint名称
        stompClient = Stomp.over(socket);//使用stomp的子协议websocket客户端
        stompClient.connect({}, function (frame) {//连接websocket服务端
            setConnected(true);
            console.log("Connected: " + frame);
            stompClient.subscribe('/topic/getResponse', function (response) {//订阅服务端消息,控制器@SendTo中定义的
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected")
    }


    function sendName() {
        var name = $("#name").val();
        stompClient.send("/welcome", {}, JSON.stringify({"name": name}));//向服务端发消息,这个是在控制器@MessageMapping中定义的

    }

    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }

</script>

</body>
</html>
